package com.mimiwang.user.service.impl;

import com.google.common.base.Strings;
import com.mimiwang.common.utils.RandomCodeUtil;
import com.mimiwang.common.utils.TokenUtil;
import com.mimiwang.user.dao.UserDao;
import com.mimiwang.user.dao.UserInfoDao;
import com.mimiwang.user.entity.UserInfoEntity;
import com.mimiwang.user.exception.NullValidateCodeException;
import com.mimiwang.user.exception.ValidateCodeErrorException;
import com.mimiwang.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @AUTHOR:游李滨
 * @DATE:2023/4/28 14:18
 */

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UserInfoDao userInfoDao;

    @Autowired
    UserDao userDao;
    @Override
    public String loginByEmail(String email, String code) throws Exception {

//        TODO 生产环境使用
//        String key="loginEmailCode:" + email;
//        Object o = redisTemplate.opsForValue().get(key);
//        if(o==null){
//            throw new NullValidateCodeException("找不到该验证码:"+key);
//        }
//        String s = String.valueOf(o);

//        TODO 测试环境使用
        String s = "admin";

        if(!s.equals(code)){
            throw new ValidateCodeErrorException("验证码错误");
        }

        UserInfoEntity user = userDao.selectUserByEmail(email);
        if (user == null){
//            新增用户，同时设置email字段
             user=new UserInfoEntity();
             user.setEmail(email);
             this.insertUser(user);
        }
//        Boolean delete = redisTemplate.delete(key);
        return TokenUtil.generateToken(user.getUserId());

    }
    private static String generateDefaultUserName(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String format = simpleDateFormat.format(new Date());
        return RandomCodeUtil.generateRandomCode(6)+format;

    }

    @Override
    public int insertUser(UserInfoEntity userInfoEntity) {
        if (Strings.isNullOrEmpty(userInfoEntity.getUserName())){
            userInfoEntity.setUserName(generateDefaultUserName());
        }

        return userDao.insertUser(userInfoEntity);
    }
}
